package main

import (
	"fmt"
	"github.com/micro/cli/v2"
	"github.com/micro/go-micro/v2"
	"log"
	"runtime"

	"kop/framework/broker"
	"kop/framework/conf"
	"kop/framework/wrapper"
	"kop/libs/database"
	"kop/libs/redis"
	"kop/modules/captain/entity"
	"kop/pb/service"
	log2 "kop/util/log"

	entity3 "kop/modules/building/entity"
	buildingH "kop/modules/building/handler"
	captainH "kop/modules/captain/handler"
	entity2 "kop/modules/maid/entity"
	maidH "kop/modules/maid/handler"
)

func main() {

	runtime.GOMAXPROCS(2)

	conf.Init()
	log2.SetLevel(conf.Log.Level)

	if err := redis.Init(conf.Redis.Address, conf.Redis.MaxIdle, conf.Redis.MaxActive); err != nil {
		panic(fmt.Errorf("redis error: %w", err))
	}

	var srv = micro.NewService(
		micro.Name("go.micro.srv.captain"),
		micro.WrapHandler(wrapper.NewLogWrapper),
		micro.Action(func(c *cli.Context) error {
			return broker.Init(c.String("broker_address"))
		}),
		micro.AfterStart(
			func() error {
				log.Println("启动船长服务器.")
				return nil
			}),
	)

	// Initialise service
	srv.Init()

	database.DB = database.Open(conf.DataBase.Dsn, conf.DataBase.MaxIdle, conf.DataBase.MaxOpen, conf.DataBase.Log)
	defer database.DB.Close()

	database.DB.AutoMigrate(new(entity.Captain))
	database.DB.AutoMigrate(new(entity.TrainSeat))
	database.DB.AutoMigrate(new(entity2.Maid))
	database.DB.AutoMigrate(new(entity2.MaidDate))
	database.DB.AutoMigrate(new(entity2.Intimacy))
	database.DB.AutoMigrate(new(entity2.Garden))
	database.DB.AutoMigrate(new(entity2.GardenMaid))
	database.DB.AutoMigrate(new(entity3.Building))
	database.DB.AutoMigrate(new(entity3.Dispatch))

	// Register handler
	_ = service.RegisterCaptainServiceHandler(srv.Server(), new(captainH.CaptainServiceHandler))
	_ = service.RegisterMaidServiceHandler(srv.Server(), new(maidH.MaidServiceHandler))
	_ = service.RegisterBuildingServiceHandler(srv.Server(), new(buildingH.BuildingServiceHandler))

	// Run service
	if err := srv.Run(); err != nil {
		panic(err)
	}
}
